﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Win32;
using System.IO;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Windows;
using XYAC.Framework.MonitorTireMaterialManual.DataExporter;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.Converters;
using System.Windows.Media;
using XYAC.Framework.MonitorTireMaterialManual.common;

namespace XYAC.Framework.MonitorTireMaterialManual.ViewModels
{
    /// <summary>
    /// 三角胶
    /// 关于班次的处理，具体的场景是：
    /// 1、机制规定。例如每个班次应该做班前检点，这种处理应到点执行；
    /// 2、工作绩效。例如工作人员上下班，会存在一些调整、协调，检查发生在哪个班次，就可以由
    /// 工作人员来选定，以确定工作量发生在哪个班次。
    /// 实现的考虑就应该有两种处理：
    /// 1、理论计算，在合适的场景中使用；
    /// 2、人工干预，可以由人为确定（选定）当前班次，覆盖自动计算。
    /// 其他考虑：
    /// 1、实际上没条工作成果记录，如质检记录，其中都会记录质检动作发生的时间，本可以推算是
    /// 理论班次，而班次字段所记录的，无非是实际工作的班次。
    /// 以上备忘文字，看似简单班次计算，由于使用场景不同，也有额外的需求需要考虑。
    /// 
    /// </summary>
    public partial class SemiSteelTriangleRubberViewModel : ViewModelBase
    {
        private double _TotalPlanQty1;

        public double TotalPlanQty1
        {
            get => _TotalPlanQty1; set => SetProperty(ref _TotalPlanQty1, value);
        }

        /// <summary>
        /// 临时数据交换目录。
        /// 保存用户选择的最近一次的数据目录。
        /// 重启软件会丢失此目录而采用固定的初始目录。
        /// </summary>
        static string tempDataSwapFolder = "";
        /// <summary>
        /// 主观判断 是 不是
        /// </summary>
        private List<Item> mindCheck;
        public List<Item> MindCheckList
        {
            get => mindCheck;
            set => SetProperty(ref mindCheck, value);
        }

        /// <summary>
        /// 主观判断 合格 还是不合格
        /// </summary>
        private List<Item> mindPassList;
        public List<Item> MindPassList
        {
            get => mindPassList;
            set => SetProperty(ref mindPassList, value);
        }

        /// <summary>
        /// 班次清单
        /// </summary>
        private List<Item> shiftList;
        public List<Item> ShiftList
        {
            get => shiftList;
            set => SetProperty(ref shiftList, value);
        }


        public static string TempDataSwapFolder
        {
            get => tempDataSwapFolder;
            set => tempDataSwapFolder = value;
        }
        //[ObservableProperty]
        //private YB_LOT_INSPECT_Local _curentInspect;
        public QualityDataUploadViewModel? UploadViewModel { get; set; }
        public IOptionsMonitor<AppConfig> AppConfig { get; }
        public SemiSteelTreadScanViewModel ViewModel { get; }

        private IServiceProvider provider;
        [ObservableProperty]
        private string _scanDatetime;
        public ILogger Logger { get; }
        [ObservableProperty]
        public SemiSteelTriangleRubberReport _semiSteelTriangleRubberReport;
        public DataFile DataFile { get; private set; }
        public Action CloseWindow { get; internal set; }

        public SemiSteelTriangleRubberViewModel(IOptionsMonitor<AppConfig> appConfig, ILogger<SemiSteelTriangleRubberViewModel> logger, IServiceProvider provider)
        {
            AppConfig = appConfig;
            this.provider = provider;
            UploadViewModel = provider.GetService<QualityDataUploadViewModel>();

            this.Logger = logger;
            this.UserId = this.AppConfig.CurrentValue.UserId;

            TotalPlanQty1 = 0.45;
            ScanDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            MindCheckList = new List<Item>();
            MindCheckList.Add(new Item("√", "True"));
            MindCheckList.Add(new Item("×", "False"));

            MindPassList = new List<Item>();
            MindPassList.Add(new Item("合格", "True"));
            MindPassList.Add(new Item("不合格", "False"));

            ShiftList = new List<Item>();
            ShiftList.Add(new Item("早班", "早"));
            ShiftList.Add(new Item("夜班", "夜"));
            //看用户怎么选，是本地优先（即用户选定优先） 还是中间表优先(已确定 以用户选择为准)
            this.CurrentShift = this.AppConfig.CurrentValue.CurrentShift;

            //this.CurrentShiftItem = findByName(this.CurrentShift);
        }

        private Item findByName(string name)
        {
            foreach (var item in ShiftList)
            {
                if (item.Value.Equals(name))
                    return item;
            }
            return null;
        }

        bool maySave = false;
        /// <summary>
        /// 打开txt报表数据
        /// </summary>
        [RelayCommand]
        private async void OpenReportData1()
        {
            try
            {
                if (!isPrecheck())
                {
                    MessageBox.Show("请先执行本班次今日的班前检点！", "应用提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string tempDir = TempDataSwapFolder;
                if (string.IsNullOrEmpty(tempDir))
                    tempDir = this.AppConfig.CurrentValue.Folder3Path;
                // 创建并配置 OpenFileDialog 对象
                var openFileDialog = new OpenFileDialog
                {
                    InitialDirectory = tempDir,
                    Title = "Open Text File",
                    Filter = "文本文件 (*.txt)|*.txt",
                    Multiselect = false
                };
                List<string> errors = null;
                // 显示文件选择对话框
                if (openFileDialog.ShowDialog() == true)
                {
                    string fileName = openFileDialog.FileName;
                    FileInfo fileInfo = new FileInfo(fileName);
                    TempDataSwapFolder = fileInfo.DirectoryName;

                    this.AppConfig.CurrentValue.Folder3Path = TempDataSwapFolder;
                    SaveNewJsonConfig();

                    // 加载并解析数据文件
                    this.DataFile = DataFileParser.LoadFromFile(fileName);

                    if (DataFile.Validate(out errors))
                    {
                        maySave = true;
                        this.SemiSteelTriangleRubberReport = new SemiSteelTriangleRubberReport();
                        SemiSteelTriangleRubberReport.PropertyChanged += SemiSteelTriangleRubberReport_PropertyChanged;
                       
                      
                        //验证成功,赋值给本地视图模型
                        this.SemiSteelTriangleRubberReport = new()
                        {
                            SerialNumber = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER,
                            ScanedDatetime = ScanDatetime,  //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            PlanId = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER,
                            Shift = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SHIFT,
                            SpecNameInfact = UploadViewModel.CurrentUserChoicePlan?.InspectModel.PART_NUMBER,
                            Eqp = UploadViewModel.CurrentUserChoicePlan?.InspectModel.EQP,
                            PlanDate = UploadViewModel.CurrentUserChoicePlan.InspectModel.PLAN_DATE.Value,

                            SpecName = this.DataFile.TypeName,

                            /* 三角胶 没有以下数据
                            TotalArea = DataFile.Area,//总面积
                            TotalLeftArea = DataFile.LeftArea,
                            TotalRightArea = DataFile.RightArea,
                            MeasureArea = DataFile.MeasureArea,
                            MeasureLeftArea = DataFile.MeasureLeftArea,
                            MeasureRightArea = DataFile.MeasureRightArea,
                            AreaPercent = Math.Round(((DataFile.MeasureArea - DataFile.Area) / DataFile.Area) * 100F, 2),
                            */
                            //4
                            TotalWidth_Stable = _data7(), //DataFile.StableKeys.LastOrDefault().Coordinate,
                                                          //5
                            TotalWidth_Scan = _data9(),// DataFile.MeasureKeys.LastOrDefault().Coordinate,
                                                       //6 第三行
                                                       //TotalThickness_Stable = DataFile.StableKeys.LastOrDefault().Value,

                            TotalThickness_Stable = _data10(),// DataFile.StableKeys.Count > 2 ? DataFile.StableKeys[2].Value : DataFile.StableKeys.LastOrDefault().Value,
                                                              //7 第三行
                                                              //TotalThickness_Scan = DataFile.MeasureKeys.LastOrDefault().Value,
                            TotalThickness_Scan = _data12(),// DataFile.MeasureKeys[2].Value,
                                                            //8
                            TotalThickness_Points = _data15(),//DataFile.MeasureKeys.FirstOrDefault().Value,
                                                              //9
                            AngleThickness_Stable = _data16(),//DataFile.StableKeys.Skip(1).FirstOrDefault().Value,
                                                              //10
                            AngleThickness_Scan = _data18(),//DataFile.MeasureKeys.Skip(1).FirstOrDefault().Value,
                                                            //11 第三行
                                                            //AngleWidth_Stable = Math.Abs(DataFile.StableKeys[2].Coordinate - DataFile.StableKeys[1].Coordinate),
                                                            //AngleWidth_Stable = Math.Abs(DataFile.StableKeys.Skip(1).LastOrDefault().Coordinate - DataFile.StableKeys.Skip(1).FirstOrDefault().Coordinate),
                            AngleWidth_Stable = _data19(),//Math.Abs(DataFile.StableKeys.Skip(1).LastOrDefault().Coordinate - DataFile.StableKeys[1].Coordinate),
                                                          //12 第三行
                                                          //AngleWidth_Scan = Math.Abs(DataFile.MeasureKeys.Skip(1).LastOrDefault().Coordinate - DataFile.XReference),
                                                          //AngleWidth_Scan = Math.Abs(DataFile.MeasureKeys[2].Coordinate - DataFile.XReference),
                            AngleWidth_Scan = _data21(),//Math.Abs(DataFile.MeasureKeys.Skip(1).LastOrDefault().Coordinate - DataFile.MeasureKeys[1].Coordinate),
                                                        //CrossSectionShape = "True",
                                                        //PassStatus = "True",
                            Data10 = _data10(),
                            Data12 = _data12(),
                            Data15 = _data15(),
                            Data16 = _data16(),
                            Data18 = _data18(),
                            Data19 = _data19(),
                            Data21 = _data21(),
                            Data7 = _data7(),
                            Data9 = _data9(),
                            DataFileJson = JsonSerializeHelper.SerializeObjectToJson(DataFile),
                        };

                        this.SemiSteelTriangleRubberReport.PropertyChanged += SemiSteelTriangleRubberReport_PropertyChanged;
                        //initCheck();
                        /*
                       if (DataFile.StableKeys.Count >= 3)
                           this.SemiSteelTriangleRubberReport.TotalThickness_Stable = DataFile.StableKeys[2].Value;
                       else
                           this.SemiSteelTriangleRubberReport.TotalThickness_Stable = 0;
                       if (DataFile.MeasureKeys.Count >= 3)
                           SemiSteelTriangleRubberReport.TotalThickness_Scan = DataFile.MeasureKeys[2].Value;
                       else
                           SemiSteelTriangleRubberReport.TotalThickness_Scan = 0;

                       if (DataFile.StableKeys.Count >= 3)
                           SemiSteelTriangleRubberReport.AngleWidth_Stable = Math.Abs(DataFile.StableKeys[2].Coordinate - DataFile.StableKeys[1].Coordinate);
                       else
                           SemiSteelTriangleRubberReport.AngleWidth_Stable = Math.Abs(DataFile.StableKeys[2].Coordinate - DataFile.StableKeys[1].Coordinate);
                       */
                    }
                    else
                    {
                        //弹出exception
                        MessageBox.Show("文件验证失败:\n" + string.Join("\n", errors), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Logger?.LogError(ex.Message, ex);
                MessageBox.Show("打开文件时出现错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        [RelayCommand]
        private async void OpenReportData()
        {
            try
            {
                if (!isPrecheck())
                {
                    MessageBox.Show("请先执行本班次今日的班前检点！", "应用提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                string tempDir = TempDataSwapFolder;
                if (string.IsNullOrEmpty(tempDir))
                    tempDir = this.AppConfig.CurrentValue.Folder3Path;
                // 创建并配置 OpenFileDialog 对象
                var openFileDialog = new OpenFileDialog
                {
                    InitialDirectory = tempDir,
                    Title = "Open Text File",
                    Filter = "文本文件 (*.txt)|*.txt",
                    Multiselect = false
                };
                List<string> errors = null;
                // 显示文件选择对话框
                if (openFileDialog.ShowDialog() == true)
                {
                    string fileName = openFileDialog.FileName;
                    FileInfo fileInfo = new FileInfo(fileName);
                    TempDataSwapFolder = fileInfo.DirectoryName;

                    this.AppConfig.CurrentValue.Folder3Path = TempDataSwapFolder;
                    SaveNewJsonConfig();

                    // 加载并解析数据文件
                    this.DataFile = DataFileParser.LoadFromFile(fileName);

                    if (DataFile.Validate(out errors))
                    {
                        maySave = true;
                        this.SemiSteelTriangleRubberReport = new SemiSteelTriangleRubberReport();
                        SemiSteelTriangleRubberReport.PropertyChanged += SemiSteelTriangleRubberReport_PropertyChanged;


                        //验证成功,赋值给本地视图模型
                        this.SemiSteelTriangleRubberReport.SerialNumber = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER;
                        this.SemiSteelTriangleRubberReport.ScanedDatetime = ScanDatetime;
                        this.SemiSteelTriangleRubberReport.PlanId = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SERIAL_NUMBER;
                        this.SemiSteelTriangleRubberReport.Shift = UploadViewModel.CurrentUserChoicePlan?.InspectModel.SHIFT;
                        this.SemiSteelTriangleRubberReport.SpecNameInfact = UploadViewModel.CurrentUserChoicePlan?.InspectModel.PART_NUMBER;
                        this.SemiSteelTriangleRubberReport.Eqp = UploadViewModel.CurrentUserChoicePlan?.InspectModel.EQP;
                        this.SemiSteelTriangleRubberReport.PlanDate = UploadViewModel.CurrentUserChoicePlan.InspectModel.PLAN_DATE.Value;

                        this.SemiSteelTriangleRubberReport.SpecName = this.DataFile.TypeName;
                        this.SemiSteelTriangleRubberReport.TotalWidth_Stable = _data7(); //DataFile.StableKeys.LastOrDefault().Coordinate,
                                                                                         //5
                        this.SemiSteelTriangleRubberReport.TotalWidth_Scan = _data9();// DataFile.MeasureKeys.LastOrDefault().Coordinate,
                                                                                      //6 第三行
                                                                                      //TotalThickness_Stable = DataFile.StableKeys.LastOrDefault().Value,

                        this.SemiSteelTriangleRubberReport.TotalThickness_Stable = _data10();// DataFile.StableKeys.Count > 2 ? DataFile.StableKeys[2].Value : DataFile.StableKeys.LastOrDefault().Value,
                                                                                             //7 第三行
                                                                                             //TotalThickness_Scan = DataFile.MeasureKeys.LastOrDefault().Value,
                        this.SemiSteelTriangleRubberReport.TotalThickness_Scan = _data12();// DataFile.MeasureKeys[2].Value,
                                                                                           //8
                        this.SemiSteelTriangleRubberReport.TotalThickness_Points = _data15();//DataFile.MeasureKeys.FirstOrDefault().Value,
                                                                                             //9
                        this.SemiSteelTriangleRubberReport.AngleThickness_Stable = _data16();//DataFile.StableKeys.Skip(1).FirstOrDefault().Value,
                                                                                             //10
                        this.SemiSteelTriangleRubberReport.AngleThickness_Scan = _data18();//DataFile.MeasureKeys.Skip(1).FirstOrDefault().Value,
                                                                                           //11 第三行
                                                                                           //AngleWidth_Stable = Math.Abs(DataFile.StableKeys[2].Coordinate - DataFile.StableKeys[1].Coordinate),
                                                                                           //AngleWidth_Stable = Math.Abs(DataFile.StableKeys.Skip(1).LastOrDefault().Coordinate - DataFile.StableKeys.Skip(1).FirstOrDefault().Coordinate),
                        this.SemiSteelTriangleRubberReport.AngleWidth_Stable = _data19();//Math.Abs(DataFile.StableKeys.Skip(1).LastOrDefault().Coordinate - DataFile.StableKeys[1].Coordinate),
                                                                                         //12 第三行
                                                                                         //AngleWidth_Scan = Math.Abs(DataFile.MeasureKeys.Skip(1).LastOrDefault().Coordinate - DataFile.XReference),
                                                                                         //AngleWidth_Scan = Math.Abs(DataFile.MeasureKeys[2].Coordinate - DataFile.XReference),
                        this.SemiSteelTriangleRubberReport.AngleWidth_Scan = _data21();//Math.Abs(DataFile.MeasureKeys.Skip(1).LastOrDefault().Coordinate - DataFile.MeasureKeys[1].Coordinate),
                                                                                       //CrossSectionShape = "True",
                                                                                       //PassStatus = "True",
                        this.SemiSteelTriangleRubberReport.Data10 = _data10();
                        this.SemiSteelTriangleRubberReport.Data12 = _data12();
                        this.SemiSteelTriangleRubberReport.Data15 = _data15();
                        this.SemiSteelTriangleRubberReport.Data16 = _data16();
                        this.SemiSteelTriangleRubberReport.Data18 = _data18();
                        this.SemiSteelTriangleRubberReport.Data19 = _data19();
                        this.SemiSteelTriangleRubberReport.Data21 = _data21();
                        this.SemiSteelTriangleRubberReport.Data7 = _data7();
                        this.SemiSteelTriangleRubberReport.Data9 = _data9();
                        this.SemiSteelTriangleRubberReport.DataFileJson = JsonSerializeHelper.SerializeObjectToJson(DataFile);
                    }
                    else
                    {
                        //弹出exception
                        MessageBox.Show("文件验证失败:\n" + string.Join("\n", errors), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Logger?.LogError(ex.Message, ex);
                MessageBox.Show("打开文件时出现错误: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void initCheck()
        {
            var fss = PropertyNameConverter.GetFormattedPropertyComments_v4(this.SemiSteelTriangleRubberReport);
            for (var i = 0; fss.Length > i; i++)
            {
                OnPropertyChanged(fss[i].Name);
            }
        }

        private void SemiSteelTriangleRubberReport_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "TotalWidth_Scan" || e.PropertyName == "TotalWidth_Stable")
            {
                OnPropertyChanged(nameof(TotalWidthTextColor)); // 触发颜色更新
            }
            if (e.PropertyName == "TotalThickness_Scan" || e.PropertyName == "TotalThickness_Stable")
            {
                OnPropertyChanged(nameof(TotalThicknessTextColor)); 
            }
            if (e.PropertyName == "AngleThickness_Scan" || e.PropertyName == "AngleThickness_Stable")
            {
                OnPropertyChanged(nameof(AngleThickness_ScanTextColor)); 
            }
            if (e.PropertyName == "AngleWidth_Scan" || e.PropertyName == "AngleWidth_Stable")
            {
                OnPropertyChanged(nameof(AngleWidth_ScanTextColor)); 
            }
            if (e.PropertyName == "TotalThickness_Points")
            {
                OnPropertyChanged(nameof(TotalThickness_PointsTextColor));
            }
        }

        /// <summary>
        /// 上传当前条码以及关联数据到远程数据库,同时记录到本地数据记录
        /// </summary>
        [RelayCommand]
        private void UploadCurrentData()
        {
            if (!maySave)
            {
                MessageBox.Show("请先选择扫描的文本文件进行解析");
                return;
            }
            if (this.SemiSteelTriangleRubberReport is null)
            {
                MessageBox.Show("请上传报表数据进行解析", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if (string.IsNullOrEmpty(SemiSteelTriangleRubberReport.CrossSectionShape))
            {
                MessageBox.Show("请选择断面形状", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if (string.IsNullOrEmpty(this.UserId) || this.UserId.Trim().Length > 8)
            {
                MessageBox.Show("检测员ID不合法", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            this.SemiSteelTriangleRubberReport.UserId = this.UserId;
            this.SemiSteelTriangleRubberReport.Shift = this.CurrentShift;

            //this.SemiSteelTriangleRubberReport.CrossSectionShape = this.CrossSectionShape;
            //this.SemiSteelTriangleRubberReport.PassStatus = this.PassStatus;
            //this.SemiSteelTriangleRubberReport.Remark = this.Remark;
            //this.SemiSteelTriangleRubberReport.SpecNameInfact = this.CurentInspect.PART_NUMBER;

            //此处用于同步到本地库
            //插入本地库
            //更新中间表状态
            //"确实要上报数据！";//
            var msg = PropertyNameConverter.GetFormattedPropertyComments_v2(this.SemiSteelTriangleRubberReport);
            if (MessageBox.Show(msg, "上报数据", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                using (var scope = this.provider.CreateScope())
                {
                    var reportService = scope.ServiceProvider.GetService<ILocalReportService>();
                    var uploadViewModel = scope.ServiceProvider.GetService<QualityDataUploadViewModel>();
                    int ret = reportService.Add<SemiSteelTriangleRubberReport>(this.SemiSteelTriangleRubberReport, uploadViewModel.CurrentUserChoicePlan.InspectModel);

                    if (ret == 0)
                    {
                        MessageBox.Show("保存数据失败,请稍后重试");
                    }
                    else
                    {
                        //关闭窗体
                        this.CloseWindow?.Invoke();
                    }
                }
            }
        }
        /// <summary>
        /// 检查是否已做过班前检点。
        /// </summary>
        /// <returns>已做过，返回真</returns>
        public bool isPrecheck()
        {
            using var scope = this.provider.CreateScope();
            var reportService = scope.ServiceProvider.GetService<ILocalReportService>();
            this.CurrentShift = this.AppConfig.CurrentValue.CurrentShift;
            var CurrentShift = AppConfig.CurrentValue.GetCurrentShift();
            var dt = AppConfig.CurrentValue.GetCurrentProcuceDate();
            return reportService.isCheck(CurrentShift, dt);
        }


        internal void UpdateUserId(string text)
        {
            try
            {
                this.AppConfig.CurrentValue.UserId = text;
                SaveNewJsonConfig();
            }
            catch (Exception ex)
            {
                Logger?.LogError("保存用户ID失败", ex);
            }
        }

        internal void UpdateCurrentShift(string text)
        {
            try
            {
                this.AppConfig.CurrentValue.CurrentShift = text;
                SaveNewJsonConfig();
            }
            catch (Exception ex)
            {
                Logger?.LogError("保存当前班次失败！", ex);
            }
        }

        private void SaveNewJsonConfig()
        {
            try
            {
                const string configPath = "./Configs/";
                const string configFileName = "AppConfig.json";
                const string tempFileName = "AppConfig_temp.json";

                string configFullPath = Path.Combine(configPath, configFileName);
                string tempFullPath = Path.Combine(configPath, tempFileName);

                // 复制原始配置文件到临时文件
                File.Copy(configFullPath, tempFullPath, overwrite: true);
                var currentValue = this.AppConfig.CurrentValue.Clone();
                // 修改临时文件
                JsonObject appSetting;
                using (FileStream fs = new FileStream(tempFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    appSetting = JsonNode.Parse(fs).AsObject();

                    // 将当前的 CurrentAppConfig 序列化为 JsonNode
                    JsonNode sourceJsonNode = JsonSerializer.SerializeToNode(currentValue);

                    // 替换 "AppConfig" 节点
                    appSetting["AppConfig"] = sourceJsonNode;

                    // 清空文件并重置位置
                    fs.SetLength(0);
                    fs.Position = 0;

                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true // 格式化输出
                    };
                    JsonSerializer.Serialize(fs, appSetting, options);
                }

                // 原子性地替换原始配置文件
                File.Replace(tempFullPath, configFullPath, null);
            }
            catch (Exception ex)
            {
                this.Logger.LogError("保存配置文件失败", ex);
            }
        }

        [ObservableProperty]
        private string _userId;


        [ObservableProperty]
        private string _crossSectionShape;
        [ObservableProperty]
        private string _specNameInfact;
        [ObservableProperty]
        private string _eqp;
        [ObservableProperty]
        private string _scanedDatetime;
        [ObservableProperty]
        private string _serialNumber;

        /// <summary>
        /// 当前班次
        /// </summary>
        [ObservableProperty]
        private string _currentShift;

        [ObservableProperty]
        private Item _currentShiftItem;
        /// <summary>
        /// 宽度(mm) 标准
        /// SemiSteelTriangleRubberReport.TotalWidth_Stable
        /// TXT文档，[Keys]下面最后一行的左边数字
        /// </summary>
        private float _data7()
        {
            return (float)DataFile.StableKeys.LastOrDefault().Coordinate;
        }
        /// <summary>
        /// 宽度(mm) 实测
        /// TXT文档，[MeasureKeys]下面最后一行的左边数字
        /// SemiSteelTriangleRubberReport.TotalWidth_Scan
        /// </summary>
        private float _data9()
        {
            return (float)DataFile.MeasureKeys.LastOrDefault().Coordinate;
        }

        /// <summary>
        /// 厚度(mm) 标准
        /// 分四种情况：
        /// 1、Keys行数=2
        /// TXT文档，[Keys]下面最后一行的右边数字
        /// 2、Keys行数=3并且[keys]最后一行右边等于0
        /// TXT文档，[Keys]下面倒数第二行的右边数字
        /// 3、Keys行数=3并且[keys]最后一行右边不等于0
        /// TXT文档，[Keys]下面最后一行的右边数字
        /// 4、Keys行数=4
        /// TXT文档，[Keys]下面倒数第二行的右边数字
        /// SemiSteelTriangleRubberReport.TotalThickness_Stable
        /// </summary>
        private double _data10()
        {
            int total = DataFile.StableKeys.Count;
            if (total == 2)
            {
                return DataFile.StableKeys.LastOrDefault().Value;
            }
            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {
                    return DataFile.StableKeys[total - 2].Value;
                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    return (float)DataFile.StableKeys.LastOrDefault().Value;
                }
            }
            if (total == 4)
            {
                return DataFile.StableKeys[total - 2].Value;
            }
            return 0.0f;
        }
        /// <summary>
        /// 厚度(mm) 实测
        /// 分四种情况：
        /// 1、Keys行数=2
        /// TXT文档，[[MeasureKeys]下面倒数第二行的右边数字(废弃)
        /// TXT文档MeasureKeys下第二行右边数字（2025年6月3号反馈的）
        /// 2、Keys行数=3并且[keys]最后一行右边等于0
        /// TXT文档，[[MeasureKeys]下面倒数第二行的右边数字
        /// 3、Keys行数=3并且[keys]最后一行右边不等于0
        /// TXT文档，[[MeasureKeys]下面倒数第二行的右边数字（MesureKeys行数=4）
        /// TXT文档，[[MeasureKeys] 下面倒数第一行的右边数字（MesureKeys行数=3）
        /// 4、Keys行数=4
        /// TXT文档，[[MeasureKeys]下面倒数第二行的右边数字
        /// SemiSteelTriangleRubberReport.TotalThickness_Scan
        /// </summary>
        private double _data12()
        {
            int total = DataFile.StableKeys.Count;
            int rows = DataFile.MeasureKeys.Count;

            if (total == 2)
            {
                //return DataFile.MeasureKeys[rows - 2].Value;
                return DataFile.MeasureKeys[1].Value;
            }

            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {
                    return DataFile.MeasureKeys[rows - 2].Value;
                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    if (rows == 4)
                        return DataFile.MeasureKeys[rows - 2].Value;
                    if (rows == 3)
                        return DataFile.MeasureKeys.LastOrDefault().Value;
                }
            }
            if (total == 4)
            {
                return DataFile.MeasureKeys[rows - 2].Value;
            }
            return 0.0f;
        }

        /// <summary>
        /// 端点厚度(mm) 实测
        /// TXT文档，[MeasureKeys]下面第一行的右边数字
        /// SemiSteelTriangleRubberReport.TotalThickness_Points
        /// </summary>
        private double _data15()
        {
            return DataFile.MeasureKeys[0].Value;
        }

        /// <summary>
        /// 拐点厚度(mm) 标准
        /// 分四种情况：
        /// 1、Keys行数=2
        /// 无拐点，null
        /// 2、Keys行数=3并且[keys]最后一行右边等于0
        /// 无拐点，null
        /// 3、Keys行数=3并且[keys]最后一行右边不等于0
        /// TXT文档，[Keys]下面第二行的右边数字
        /// 4、Keys行数=4
        /// TXT文档，[Keys]下面第二行的右边数字
        /// SemiSteelTriangleRubberReport.AngleThickness_Stable
        /// </summary>
        private double _data16()
        {
            int total = DataFile.StableKeys.Count;
            if (total == 2)
            {

            }
            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {

                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    return DataFile.StableKeys[1].Value;
                }
            }
            if (total == 4)
            {
                return DataFile.StableKeys[1].Value;
            }
            return 0.0f;
        }

        /// <summary>
        /// 拐点厚度(mm) 实测
        /// 分四种情况：
        /// 1、Keys行数=2
        /// 无拐点，null
        /// 2、Keys行数=3并且[keys]最后一行右边等于0
        /// 无拐点，null
        /// 3、Keys行数=3并且[keys]最后一行右边不等于0
        /// TXT文档，[MeasureKeys]下面第二行的右边数字
        /// 4、Keys行数=4
        /// TXT文档，[MeasureKeys]下面第二行的右边数字
        /// SemiSteelTriangleRubberReport.AngleThickness_Scan
        /// </summary>
        private double _data18()
        {
            int total = DataFile.StableKeys.Count;

            if (total == 2)
            {

            }
            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {

                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    return DataFile.MeasureKeys[1].Value;
                }
            }
            if (total == 4)
            {
                return DataFile.MeasureKeys[1].Value;
            }
            return 0.0f;
        }

        /// <summary>
        /// 拐点宽度(mm) 标准
        /// TXT文档，[Keys]下面最后一行的左边数字-[Keys]下面第二行的左边数字
        /// 
        /// TXT文档，[Keys]下面最后一行的左边数字-[Keys]下面第二行的左边数字
        /// SemiSteelTriangleRubberReport.AngleWidth_Stable
        /// </summary>

        private double _data19()
        {
            int total = DataFile.StableKeys.Count;

            if (total == 2)//2与3的处理相同
            {

            }
            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {

                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    return DataFile.StableKeys.LastOrDefault().Coordinate - DataFile.StableKeys[1].Coordinate;
                }
            }
            if (total == 4)
            {
                return DataFile.StableKeys.LastOrDefault().Coordinate - DataFile.StableKeys[1].Coordinate;
            }
            return 0.0;
            //return DataFile.StableKeys.LastOrDefault().Coordinate - DataFile.StableKeys[1].Coordinate;
        }

        /// <summary>
        /// 拐点宽度(mm) 实测
        /// 分四种情况：
        /// 1、Keys行数=2
        /// 无拐点，null
        /// 2、Keys行数=3并且[keys]最后一行右边等于0
        /// 无拐点，null
        /// 3、Keys行数=3并且[keys]最后一行右边不等于0
        /// TXT文档，[Keys]下面最后一行的左边数字-TXT文档，[Keys]下面第二行的左边数字
        /// 4、Keys行数=4
        /// TXT文档，[Keys]下面最后一行的左边数字-TXT文档，[Keys]下面第二行的左边数字
        /// SemiSteelTriangleRubberReport.AngleWidth_Scan
        /// </summary>
        private double _data21()
        {
            int total = DataFile.StableKeys.Count;
            if (total == 2)
            {

            }
            if (total == 3)
            {
                if (DataFile.StableKeys.LastOrDefault().Value == 0)
                {

                }
                if (DataFile.StableKeys.LastOrDefault().Value != 0)
                {
                    return DataFile.MeasureKeys.LastOrDefault().Coordinate - DataFile.MeasureKeys[1].Coordinate;

                }
            }
            if (total == 4)
            {
                return DataFile.MeasureKeys.LastOrDefault().Coordinate - DataFile.MeasureKeys[1].Coordinate;
            }
            return 0.0f;
        }

        [ObservableProperty]
        private string _passStatus;
        [ObservableProperty]
        private string _remark;


        // ViewModel属性
        public Brush TotalWidthTextColor
        {
            get
            {
                if (SemiSteelTriangleRubberReport == null)
                    return Brushes.Black;

                var hv = SemiSteelTriangleRubberReport.TotalWidth_Stable + 2;
                var lv = SemiSteelTriangleRubberReport.TotalWidth_Stable - 2;
                var rs = util.exeCheck(SemiSteelTriangleRubberReport.TotalWidth_Scan, hv, lv);
                return rs ?  Brushes.Black:Brushes.Red;
            }
        }
        public Brush TotalThicknessTextColor
        {
            get
            {
                if (SemiSteelTriangleRubberReport == null)
                    return Brushes.Black;

                var hv = SemiSteelTriangleRubberReport.TotalThickness_Stable + 0.5;
                var lv = SemiSteelTriangleRubberReport.TotalThickness_Stable - 0.5;
                var rs = util.exeCheck(SemiSteelTriangleRubberReport.TotalThickness_Scan, hv, lv);
                return rs ? Brushes.Black : Brushes.Red;
            }
        }
        public Brush AngleThickness_ScanTextColor
        {
            get
            {
                if (SemiSteelTriangleRubberReport == null)
                    return Brushes.Black;

                var hv = SemiSteelTriangleRubberReport.AngleThickness_Stable + 0.5;
                var lv = SemiSteelTriangleRubberReport.AngleThickness_Stable - 0.5;
                var rs = util.exeCheck(SemiSteelTriangleRubberReport.AngleThickness_Scan, hv, lv);
                return rs ? Brushes.Black : Brushes.Red;
            }
        }

        public Brush AngleWidth_ScanTextColor
        {
            get
            {
                if (SemiSteelTriangleRubberReport == null)
                    return Brushes.Black;

                var hv = SemiSteelTriangleRubberReport.AngleWidth_Stable + 2;
                var lv = SemiSteelTriangleRubberReport.AngleWidth_Stable - 2;
                var rs = util.exeCheck(SemiSteelTriangleRubberReport.AngleWidth_Scan, hv, lv);
                return rs ? Brushes.Black : Brushes.Red;
            }
        }

        public Brush TotalThickness_PointsTextColor
        {
            get
            {
                if (SemiSteelTriangleRubberReport == null)
                    return Brushes.Black;
                var hv =  0.5;
                var rs = util.lessCheck(SemiSteelTriangleRubberReport.TotalThickness_Points, hv);
                return rs ? Brushes.Black : Brushes.Red;
            }
        }

        Util util=new Util();

    }
}